#include "pch.h"
#include "Tree.h"


void InitTree(Tree *t,ElemType ref)
{
	t->root = NULL;
	t->refvalue = ref;
}

void CreateTree(Tree *tree, TreeNode *&t, char *&str)
{
	if (*str == tree->refvalue)
		t= NULL;
	else {
		t = (TreeNode*)malloc(sizeof(TreeNode));
		assert(t != NULL);
		t->data = *str;
		CreateTree(tree, t->fristChild, ++str);
		CreateTree(tree, t->nextSibling, ++str);
	}
}

TreeNode* Root(Tree *t)
{
	return t->root;
}


TreeNode* FirstChild(TreeNode *t) {
	if (t == NULL)
		return NULL;
	return t->fristChild;
}
TreeNode* FirstChild(Tree *tree) {
	return FirstChild(tree->root);
}


TreeNode* NextSibling(TreeNode *t) {
	if (t == NULL)
		return NULL;
	return t->nextSibling;
}
TreeNode* NextSibling(Tree *tree) {
	return NextSibling(tree->root);
}


TreeNode* Find(TreeNode *t, ElemType key) {
	if (t == NULL)
		return NULL;
	if (t->data == key)
		return t;
	TreeNode *p = Find(t->fristChild, key);
	if (p != NULL)
		return p;
	return Find(t->nextSibling, key);
}


TreeNode* Parent(TreeNode *t, TreeNode *p)
{
	if (t == NULL || p == NULL || p == t)
		return NULL;
	TreeNode *go = t->fristChild;
	TreeNode *parent;
	while (go != NULL && go != p)
	{
		parent = Parent(go, p);
		if (parent != NULL)
			return parent;
		go = go->nextSibling;
	}
	if (go != NULL && go == p)
		return t;
	return NULL;
}